package com.mall.common.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.mall.enums.GlobalResponseEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.validation.BindingResult;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(value = JsonInclude.Include.NON_NULL)//值为null的字段不返回
public class GlobalResponse<T> {
    private Integer status;
    private String msg;
    private T data;

    public GlobalResponse(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public GlobalResponse(Integer status, T data){
        this.status = status;
        this.data = data;
    }

    public GlobalResponse(Integer status){
        this.status = status;
    }

    public static <T> GlobalResponse<T> successByData(T data) {
        return new GlobalResponse<>(GlobalResponseEnum.SUCCESS.getCode(), data);
    }

    public static <T> GlobalResponse<T> successByMsg(String msg) {
        return new GlobalResponse<>(GlobalResponseEnum.SUCCESS.getCode(), msg);
    }

    public static <T> GlobalResponse<T> success() {
        return new GlobalResponse<>(GlobalResponseEnum.SUCCESS.getCode(), GlobalResponseEnum.SUCCESS.getDescription());
    }

    public static <T> GlobalResponse<T> error(GlobalResponseEnum responseEnum) {
        return new GlobalResponse<>(responseEnum.getCode(), responseEnum.getDescription());
    }

    public static <T> GlobalResponse<T> error(GlobalResponseEnum responseEnum, String msg) {
        return new GlobalResponse<>(responseEnum.getCode(), msg);
    }

    public static <T> GlobalResponse<T> error(GlobalResponseEnum responseEnum, BindingResult bindingResult) {
        return new GlobalResponse<>(responseEnum.getCode(), bindingResult.getFieldError().getField()
                + " " + bindingResult.getFieldError().getDefaultMessage());
    }
}
